package com.valuegroup.smarttodo.ui.programme.summarize;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.PopupMenu;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.valuegroup.smarttodo.R;
import com.valuegroup.smarttodo.common.BaseViewHolder;
import com.valuegroup.smarttodo.common.CommonRecyclerAdapter;
import com.valuegroup.smarttodo.data.ServiceFactory;
import com.valuegroup.smarttodo.data.model.AppStatus;
import com.valuegroup.smarttodo.data.model.Summarize;
import com.valuegroup.smarttodo.plugins.pickdialog.DatePickDialog;
import com.valuegroup.smarttodo.plugins.pickdialog.DateUtils;
import com.valuegroup.smarttodo.plugins.pickdialog.OnCustomSureLisener;
import com.valuegroup.smarttodo.plugins.pickdialog.OnSureLisener;
import com.valuegroup.smarttodo.plugins.pickdialog.bean.DateType;
import com.valuegroup.smarttodo.ui.BaseActivity;
import com.valuegroup.smarttodo.util.AlertUtils;

import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.valuegroup.smarttodo.plugins.pickdialog.bean.DateType.TYPE_Y;
import static com.valuegroup.smarttodo.plugins.pickdialog.bean.DateType.TYPE_YM;

public class SumActivity extends BaseActivity {

    @BindView(R.id.btnBack)
    ImageButton btnBack;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.labSelectSumType)
    TextView labSelectSumType;
    @BindView(R.id.btnSelectSumType)
    LinearLayout btnSelectSumType;
    @BindView(R.id.labSelectDate)
    TextView labSelectDate;
    @BindView(R.id.btnSelectDate)
    LinearLayout btnSelectDate;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private PopupMenu menuSumType;
    private int sumType = AppStatus.SumType.DAY;
    private int rangeYear = 0;
    private int rangeMonth = 0;
    private DateType dateType = TYPE_YM;
    private SumContentAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sum);
        ButterKnife.bind(this);

        // 初始化工具条
        setSupportActionBar(toolbar);
        // 隐藏Toolbar的标题栏
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        initView();
    }

    private void initView() {

        menuSumType = new PopupMenu(this, btnSelectSumType);
        menuSumType.inflate(R.menu.menu_sumtype);
        menuSumType.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                btnSelectDate.setVisibility(View.VISIBLE);

                switch (item.getItemId()) {
                    case R.id.m1:
                        sumType = AppStatus.SumType.DAY;
                        dateType = TYPE_YM;
                        break;
                    case R.id.m2:
                        sumType = AppStatus.SumType.WEEK;
                        dateType = TYPE_Y;
                        break;
                    case R.id.m3:
                        sumType = AppStatus.SumType.MONTH;
                        dateType = TYPE_Y;
                        break;
                    case R.id.m4:
                        sumType = AppStatus.SumType.QUARTER;
                        dateType = TYPE_Y;
                        break;
                    case R.id.m5:
                        sumType = AppStatus.SumType.YEAR;
                        btnSelectDate.setVisibility(View.GONE);
                        break;
                }

                updateSelDateLab(new Date());
                labSelectSumType.setText(item.getTitle());
                refreshAllData();

                return false;
            }
        });

        // 初始化默认项
        labSelectSumType.setText(menuSumType.getMenu().findItem(R.id.m1).getTitle());
        updateSelDateLab(new Date());

        adapter = new SumContentAdapter(this, loadData());
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_sum, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(@NonNull Menu menu) {
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.m1:
                doChoiceDay(AppStatus.SumType.DAY, DateType.TYPE_YMD, null);
                break;
            case R.id.m2:
                doChoiceDay(AppStatus.SumType.WEEK, DateType.TYPE_CUSTOM_YEAR_WEEK, DateUtils.getYearWeekNumber(new Date()));
                break;
            case R.id.m3:
                doChoiceDay(AppStatus.SumType.MONTH, DateType.TYPE_YM, null);
                break;
            case R.id.m4:
                doChoiceDay(AppStatus.SumType.QUARTER, DateType.TYPE_CUSTOM_YEAR_QUARTER, DateUtils.getYearQuarterNumber(new Date()));
                break;
            case R.id.m5:
                doChoiceDay(AppStatus.SumType.YEAR, DateType.TYPE_Y, null);
                break;
        }
        return false;
    }

    public void doChoiceDay(Integer st, DateType dt, Integer startData) {
        DatePickDialog dialog = new DatePickDialog(this);
        dialog.setYearLimt(5);
        dialog.setType(dt);
        dialog.setStartDate(new Date());
        dialog.setStartData(startData);
        dialog.setOnChangeLisener(null);
        dialog.setOnSureLisener(new OnSureLisener() {
            @Override
            public void onSure(Date date) {
                //AlertUtils.showToast(SumActivity.this, DateUtils.date2str(date, dt.getFormat()));
                doCreateSum(st, date);
            }
        });
        dialog.setOnCustomSureLisener(new OnCustomSureLisener() {
            @Override
            public void onSure(Object obj) {
                //AlertUtils.showToast(SumActivity.this, obj.toString());
                doCreateSum(st, (Integer) obj);
            }
        });
        dialog.show();
    }

    public void doCreateSum(Integer sumType, Object obj) {

        Summarize sum = null;
        switch (sumType) {
            case AppStatus.SumType.DAY:
                sum = ServiceFactory.getInstance().getSummarizeService().getDefaultSummarizeForDay((Date) obj);
                break;
            case AppStatus.SumType.WEEK:
                sum = ServiceFactory.getInstance().getSummarizeService().getDefaultSummarizeForWeek(
                        Integer.parseInt(String.valueOf(obj).substring(0, 4)),
                        Integer.parseInt(String.valueOf(obj).substring(4))
                );
                break;
            case AppStatus.SumType.MONTH:
                sum = ServiceFactory.getInstance().getSummarizeService().getDefaultSummarizeForMonth(
                        DateUtils.getYear((Date) obj),
                        DateUtils.getMoth((Date) obj)
                );
                break;
            case AppStatus.SumType.QUARTER:
                sum = ServiceFactory.getInstance().getSummarizeService().getDefaultSummarizeForQuarter(
                        Integer.parseInt(String.valueOf(obj).substring(0, 4)),
                        Integer.parseInt(String.valueOf(obj).substring(4))
                );
                break;
            case AppStatus.SumType.YEAR:
                sum = ServiceFactory.getInstance().getSummarizeService().getDefaultSummarizeForYear(
                        DateUtils.getYear((Date) obj)
                );
                break;
        }

        if (sum != null) {
            sum = ServiceFactory.getInstance().getSummarizeService().checkExistAndSaveSummarize(sum);
            Intent intent = new Intent(this, SumContentActivity.class);
            intent.putExtra(PARAMS_KEY, sum.getId());
            intent.putExtra(PARAMS_POSITION, 0);
            startActivityForResult(intent, 1002);
        }

    }


    private List<Summarize> loadData() {
        return ServiceFactory.getInstance().getSummarizeService().findSummarize(sumType, rangeYear, rangeMonth);
    }

    /**
     * 更新列表所有数据
     */
    private void refreshAllData() {
        // 刷新列表数据
        adapter.refreshListData(loadData());
        // 平移到相关位置
        recyclerView.smoothScrollToPosition(0);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        refreshAllData();
    }

    @OnClick({R.id.btnBack, R.id.btnSelectSumType, R.id.btnSelectDate})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnBack:
                finishAfterTransition();
                break;
            case R.id.btnSelectSumType:
                menuSumType.show();
                break;
            case R.id.btnSelectDate:

                DatePickDialog dialog = new DatePickDialog(this);
                dialog.setYearLimt(5);
                dialog.setType(dateType);
                setDefaultVal(dialog);
                dialog.setOnChangeLisener(null);
                dialog.setOnSureLisener(new OnSureLisener() {
                    @Override
                    public void onSure(Date date) {
                        // 默认类型的回调
                        updateSelDateLab(date);
                        refreshAllData();
                    }
                });
                dialog.setOnCustomSureLisener(new OnCustomSureLisener() {
                    @Override
                    public void onSure(Object obj) {
                        // 自定义类型的回调
                        updateSelDateLab(obj);
                        refreshAllData();
                    }
                });
                dialog.show();
                break;
        }
    }

    private void updateSelDateLab(Object selObj) {
        rangeYear = DateUtils.getYear((Date) selObj);
        rangeMonth = DateUtils.getMoth((Date) selObj);

        if (dateType == TYPE_YM) {
            labSelectDate.setText((rangeMonth + "/" + rangeYear));
        } else {
            labSelectDate.setText((rangeYear + ""));
        }
    }

    private void setDefaultVal(DatePickDialog d) {
        switch (dateType) {
            case TYPE_Y:
                d.setStartDate(DateUtils.getDate(rangeYear, 1, 1, 0, 0));
                break;
            case TYPE_YM:
                d.setStartDate(DateUtils.getDate(rangeYear, rangeMonth, 1, 0, 0));
                break;
        }
    }


    class SumContentAdapter extends CommonRecyclerAdapter<Summarize> {

        public SumContentAdapter(Context context, List<Summarize> data) {
            super(context, data);
            setMainLayoutId(R.layout.item_sum_content);
        }

        @Override
        public void bindHeadView(BaseViewHolder v, int position) {

        }

        @Override
        public void bindBottomView(BaseViewHolder v, int position) {

        }

        @Override
        public void bindMainView(BaseViewHolder v, int position) {
            Summarize data = getData(position);

            // 初始化标题
            v.setText(R.id.labTitle, data.getTitle());

            // 查看内容
            v.getView(R.id.btnGoContent).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(view.getContext(), SumContentActivity.class);
                    intent.putExtra(PARAMS_KEY, data.getId());
                    intent.putExtra(PARAMS_POSITION, position);
                    startActivityForResult(intent, 1001);
                }
            });
        }

        @Override
        public void bindAppendView(BaseViewHolder v, int position) {

        }
    }
}